const state = {
  latestAlert: null,
  unreadAlertsCount: 0,
  wsConnected: false,
  unreadCount: 0,
  alertHistory: []
}

const mutations = {
  SET_LATEST_ALERT(state, alert) {
    state.latestAlert = alert
  },
  SET_UNREAD_COUNT(state, count) {
    state.unreadAlertsCount = count
    state.unreadCount = count
  },
  SET_WS_CONNECTED(state, connected) {
    state.wsConnected = connected
  },
  ADD_ALERT(state, alert) {
    state.alertHistory.unshift(alert)
    if (alert.level === 'urgent') {
      state.latestAlert = alert
      state.unreadAlertsCount++
      state.unreadCount++
    }
  },
  MARK_ALERT_READ(state, alertId) {
    const alert = state.alertHistory.find(a => a.id === alertId)
    if (alert && !alert.read) {
      alert.read = true
      state.unreadAlertsCount = Math.max(0, state.unreadAlertsCount - 1)
      state.unreadCount = Math.max(0, state.unreadCount - 1)
    }
  }
}

const actions = {
  // 获取最新告警
  async getLatestAlert({ commit }) {
    try {
      // 模拟API调用
      const mockAlert = {
        id: '1',
        type: 'medical',
        level: 'urgent',
        title: '药品过期提醒',
        message: '您的常用药品将在3天后过期，请及时补充',
        time: new Date().toISOString(),
        read: false
      }
      
      commit('SET_LATEST_ALERT', mockAlert)
      commit('SET_UNREAD_COUNT', 1)
    } catch (error) {
      console.error('获取最新告警失败:', error)
    }
  },

  // 关闭告警
  async dismissAlert({ commit }, alertId) {
    try {
      // 模拟API调用
      commit('MARK_ALERT_READ', alertId)
      commit('SET_LATEST_ALERT', null)
      return { success: true }
    } catch (error) {
      console.error('关闭告警失败:', error)
      return { success: false, error: error.message }
    }
  },

  // 连接WebSocket
  connectWebSocket({ commit }) {
    // 模拟WebSocket连接
    setTimeout(() => {
      commit('SET_WS_CONNECTED', true)
    }, 1000)
  },

  // 断开WebSocket
  disconnectWebSocket({ commit }) {
    commit('SET_WS_CONNECTED', false)
  },

  // 确认告警
  async acknowledgeAlertById({ commit }, alertId) {
    try {
      // 模拟API调用
      commit('MARK_ALERT_READ', alertId)
      return { success: true }
    } catch (error) {
      console.error('确认告警失败:', error)
      return { success: false, error: error.message }
    }
  }
}

const getters = {
  latestAlert: state => state.latestAlert,
  unreadAlertsCount: state => state.unreadAlertsCount,
  unreadCount: state => state.unreadCount,
  wsConnected: state => state.wsConnected,
  urgentAlerts: state => state.alertHistory.filter(a => a.level === 'urgent' && !a.read)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}